<?php

namespace console\controllers;
use yii\console\Controller;
use bc\model\shop\ShopUserModel;
use bc\model\h5\PrizeModel;
use bc\util\Util;
use bc\model\h5\LuckmoneyModel;

class ActivityController extends Controller
{
	
	
	/**
	 * 发送抽奖优惠券脚本
	 */
	public function actionSend()
	{
		set_time_limit(0);
		
		$PrizeModel = new PrizeModel();
		$timeCondition = time() - 1800;
		$params = 'prize_type = 1';
		$params .= ' AND send_time = 0';
		$params .= ' AND create_time <= ' . $timeCondition;
		
		$PrizeModel->sort = 'prize_id DESC';
		$list = $PrizeModel->getList($params);
		
		foreach ($list as $row)
		{
			$user_id = $this->searchUser($row['openid']);
			
			if($user_id != null)
			{
				$price = explode('元', $row['prize_content'])[0];
				
				$luckMoneyId = $this->getLuckMoneyId($price);
				
				
				if($luckMoneyId > 0)
				{
					$result = $this->sendLuckMoney($user_id, $luckMoneyId);
					$result_arr = json_decode($result, true);
					
					if($result_arr['result'] == 'success')
					{
						//更新发红包的时间
						$update_data['send_time'] = time();
						$PrizeModel->modify($update_data, $row['prize_id']);
					}
				}
			}
			
		}
		
		
	}
	
	
	public function actionNormal()
	{
		set_time_limit(0);
		
		$luckMoneyModel = new LuckmoneyModel();
		$timeCondition = time() - 1800;
		$params = 'send_time = 0';
		$params .= ' AND create_time <= ' . $timeCondition;
		
		$luckMoneyModel->sort = 'lm_id DESC';
		$list = $luckMoneyModel->getList($params);
		
		foreach ($list as $row)
		{
			$user_id = $this->searchUser($row['openid']);
				
			if($user_id != null)
			{
		
			
				$result = $this->sendLuckMoney($user_id, 14);
				$result_arr = json_decode($result, true);
					
				if($result_arr['result'] == 'success')
				{
					//更新发红包的时间
					$update_data['send_time'] = time();
					$luckMoneyModel->modify($update_data, $row['lm_id']);
				}
				
			}
				
		}
	}
	
	
	/**
	 * 
	 * @param integer|null $openId
	 */
	private function searchUser($openId)
	{
		$ShopUserModel = new ShopUserModel();
		$searchParams['wxid'] = $openId;
		$row = $ShopUserModel->getRow($searchParams);
		
		if($row)
		{
			return $row['user_id'];
		}
		else 
		{
			return null;
		}
		
	}
	
	//获取红包id
	private function getLuckMoneyId($price)
	{
		$id = 0;
		switch ($price)
		{
			case 8:
				$id = 10;
				break;
			case 18:
				$id = 11;
				break;
			case 28:
				$id = 12;
				break;
			case 58:
				$id = 13
				;
				break;
		}
		return $id;
	}
	
	
	/**
	 * 发送红包的动作
	 */
	private function sendLuckMoney($userId, $luckMoneyId)
	{
		$url = 'http://wx.zhishimama.com/shop/api.php?';
		$url .= 'act=send_redpacket_by_user&api_version=1.0&return_data=json&type_id='.$luckMoneyId;
		$user[] = $userId;
		$user = json_encode($user);
		$url .= '&userlist='.$user;
		$rs = Util::httpGet($url);
		return $rs;
	}
}

